#! python3
# 为整个文件夹创建一个 ZIP 文件，作为“快照”。
# 你希望保存不同的版本，希望 ZIP 文件的文件名每次创建时都有所变化。
# 例如 AlsPythonBook_1.zip、AlsPythonBook_2.zip、AlsPythonBook_3.zip，等等

import zipfile
import os


def doDocZip(path):
    # 确保为绝对路径
    path = os.path.abspath(path)
    basename = os.path.basename(path)

    num = 1
    while True:
        # 用要压缩的目录名加序号作为备份的zip文件名
        zipFileName = basename + "_" + str(num) + ".zip"
        if os.path.exists("./file/" + zipFileName):
            num += 1
        else:
            break

    # 创建备份zip文件
    print('Creating %s...' % zipFileName)
    backZip = zipfile.ZipFile("./file/" + zipFileName, 'w')

    # 遍历需要备份的目录，写入zip文件
    for folderName, subFolders, fileNames in os.walk(path):
        # folderName:当前目录名称的字符串
        if len(os.listdir(folderName)) >= 1:  # 空目录不压缩
            print('Adding files in %s...' % folderName)
            backZip.write(folderName, folderName)

        # 当前目录中文件名称的字符串列表
        for filename in fileNames:
            if filename.startswith(basename) and filename.endswith(".zip"):
                continue
            else:
                backZip.write(os.path.join(folderName, filename), compress_type=zipfile.ZIP_DEFLATED)

    backZip.close()
    print('Done.')


if __name__ == '__main__':
    doDocZip(os.getcwd())
